package com.xiaomaoguai.fcp.pre.kepler.sftp.utils;

import lombok.experimental.UtilityClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;

import java.util.Iterator;
import java.util.Map;

/**
 * @author WeiHui
 * @version v1.0.0
 * @date 2019/4/17 21:15
 * @since JDK 1.8
 */
@UtilityClass
public class BeanManager {

	private static Logger logger = LoggerFactory.getLogger(BeanManager.class.getName());

	public static synchronized void addToBeanFactory(ApplicationContext context, String className, String beanName, Map<String, Object> propertyValueMap) {
		try {
			ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) context;
			DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext.getBeanFactory();
			if (!beanFactory.containsBean(beanName)) {
				BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(className);
				if (!propertyValueMap.isEmpty()) {
					Iterator var7 = propertyValueMap.entrySet().iterator();

					while (var7.hasNext()) {
						Map.Entry<String, String> entry = (Map.Entry) var7.next();
						beanDefinitionBuilder.addPropertyValue(entry.getKey(), entry.getValue());
					}
				}

				beanDefinitionBuilder.setInitMethodName("init");
				beanFactory.registerBeanDefinition(beanName, beanDefinitionBuilder.getBeanDefinition());
				logger.info("Add {} to bean container.", beanName);
			}
		} catch (Exception var9) {
			logger.error("add bean error,className:{},beanName:{}", new Object[]{className, beanName, var9});
		}
	}

	public static void destroy(ApplicationContext context, String beanName) {
		ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) context;
		DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext.getBeanFactory();
		logger.info("destroy bean " + beanName);
		if (beanFactory.containsBean(beanName)) {
			beanFactory.destroySingleton(beanName);
			beanFactory.destroyBean(beanName, beanFactory.getBean(beanName));
			beanFactory.removeBeanDefinition(beanName);
		} else {
			logger.info("No {} defined in bean container.", beanName);
		}
	}

}
